﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using XamarinToolKit.Interfaces;
using XamarinToolKit.Model;

namespace XamarinToolKit.ViewModel
{
    public class MainViewModel : ViewModelBase
    {
        private readonly IToolKitService service;
        private ObservableCollection<ToolKitMaster> gridModels;

        public MainViewModel()
        {
            service = DependencyService.Get<IToolKitService>();
            SelectionChangedCommand = new RelayCommand<ToolKitMaster>(OpenDetail);
        }


        public RelayCommand<ToolKitMaster> SelectionChangedCommand { get; set; }

        /// <summary>
        /// 首页的分组列表
        /// </summary>
        public ObservableCollection<ToolKitMaster> GridModels
        {
            get { return gridModels; }
            set
            {
                gridModels = value;
                RaisePropertyChanged();
            }
        }

        async void OpenDetail(ToolKitMaster master)
        {
            if (master != null)
            {
                //设置我们分组当中所有的数据，以便于打开详细页面的时候保存这个信息
                var inf = new ToolKitInfo();
                inf.Master = master;
                inf.Details = new ObservableCollection<ToolKitDetail>();
                var details = await service.GetToolKitDetailsAsync(master.Id);
                details?.ForEach(item =>
                {
                    inf.Details.Add(item);
                });
                Messenger.Default.Send(inf, "OpenDetailView");
            }
        }

        public async Task InitMasterDataAsync()
        {
            var masters = await service.GetToolKitMastersAsync();
            masters?.ForEach(item =>
            {
                GridModels.Add(item);
            });
        }
    }
}
